package com.lonni.rpc.core.register;

import com.lonni.rpc.core.register.model.Service;
import com.lonni.rpc.core.register.model.ServiceURL;
import org.springframework.util.CollectionUtils;
import sun.net.util.IPAddressUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 存放所有服务相关的本地缓存
 *
 * @author: Lonni
 * @date: 2024/7/9 0009 16:57
 */
public class ServiceCache implements Serializable {

    /**
     * 本地存储所有服务实例
     * 一个服务可能有多个实现
     */
    public final static Map<Service, List<ServiceURL>> SERVICE_URLS = new ConcurrentHashMap<>();


    /**
     * 用户存储服务提供者spring bean对象
     * key: 接口名+分组+版本,例: com.lonni.rpc.core.register.xxx:1.0:default
     * value:spring的bean对象
     */
    final static Map<String, Object> BEAN_CACHES = new ConcurrentHashMap<>();

    public static void addService(Service service, ServiceURL url) {
        List<ServiceURL> serviceURLS = SERVICE_URLS.get(service);
        if (CollectionUtils.isEmpty(serviceURLS)) {
            SERVICE_URLS.put(service, new ArrayList<ServiceURL>() {{
                add(url);
            }});
        } else {
            serviceURLS.add(url);
        }

    }


    public static void addBean(Service service, Object bean) {
        String key = service.getInterfaceName() + ":" + service.getVersion() + ":" + service.getGroup();
        BEAN_CACHES.putIfAbsent(key, bean);
    }

    public static Object getBean(String key) {
        return BEAN_CACHES.getOrDefault(key, null);
    }
    public static Object getBean(Service service) {
        String key = service.getInterfaceName() + ":" + service.getVersion() + ":" + service.getGroup();
        return BEAN_CACHES.getOrDefault(key, null);
    }
}



